<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="70%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-card>
        <template #header> 基本信息 </template>
        <el-row>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="formData.mobile" placeholder="请输入手机" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="渠道" prop="source">
              <el-select
                v-model="formData.source"
                clearable
                placeholder="请选择渠道"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.CRM_CUSTOMER_SOURCE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="8">
            <el-form-item label="地址" prop="city" @change="handleChange">
              <el-cascader
                v-model="cityArr"
                :options="areaList"
                :props="props"
                @change="handleChange"
                style="width: 100%"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input v-model="formData.detailAddress" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="客户需求" prop="demand">
              <el-input v-model="formData.demand" placeholder="请输入需求" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="跟踪状态" prop="followStatus">
              <el-select
                v-model="formData.followStatus"
                clearable
                placeholder="请选择跟踪状态"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.CRM_FOLLOW_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                  <span :style="{ color: getFollowStatusColor(dict.label) }">{{ dict.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="跟踪人" prop="stalker">
              <el-select
                v-model="formData.stalker"
                clearable
                placeholder="请选择跟踪人"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.nickname"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求类型" prop="tags">
              <el-select
                v-model="formData.tags"
                clearable
                placeholder="请选择需求类型"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.DEMAND_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="仓位" prop="positionName">
              <el-input v-model="formData.positionName" placeholder="请输入仓位" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="门店" prop="storageName">
              <el-select
                v-model="selectedStorageId"
                clearable
                placeholder="请选门店"
                style="width: 100%"
                @change="handleStorageChange"
              >
                <el-option
                  v-for="dict in storageList"
                  :key="dict.storageId"
                  :label="dict.storageName"
                  :value="dict.storageId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签单时间" prop="signTime">
              <el-date-picker
                v-model="formData.signTime"
                type="date"
                value-format="x"
                placeholder="选择签单时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="下次回访时间" prop="nextTime">
              <el-date-picker
                v-model="formData.nextTime"
                type="date"
                value-format="x"
                placeholder="选择下次联系时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="微信" prop="weixin">
              <el-input v-model="formData.weixin" placeholder="请输入微信" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="QQ" prop="qq">
              <el-input v-model="formData.qq" placeholder="请输入QQ" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="金额" prop="inPrice">
              <el-input-number
                v-model="formData.inPrice"
                :precision="2"
                :step="0.01"
                :min="0"
                placeholder="请输入金额"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注" prop="remark">
              <el-input
                type="textarea"
                :rows="2"
                v-model="formData.remark"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { CustomerApi, CustomerVO } from '@/api/crm/crmcustomer'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'

import { BaseStorageApi, BaseStorageVO } from '@/api/crm/basestorage'
import * as AreaApi from '@/api/system/area'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'

import { getUserInfo } from '@/hooks/web/useCache'
/** 客户 表单 */
defineOptions({ name: 'CustomerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
import { ElMessage } from 'element-plus'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<Partial<CustomerVO>>({
  id: undefined,
  name: undefined,
  mobile: undefined,
  telephone: undefined,
  dealStatus: undefined,
  dealTime: undefined,
  isLock: undefined,
  level: undefined,
  industry: undefined,
  tags: undefined,
  source: undefined,
  remark: undefined,
  userId: undefined,
  province: undefined,
  city: undefined,
  area: undefined,
  detailAddress: undefined,
  lng: undefined,
  lat: undefined,
  nextTime: undefined,
  followTime: undefined,
  collectTime: undefined,
  weixin: undefined,
  qq: undefined,
  purchaseTotal: undefined,
  purchaseTimes: undefined,
  followStatus: undefined,
  demand: undefined,
  stalker: undefined,
  positionName: undefined,
  storageName: undefined,
  storageCode: undefined,
  storageId: undefined,
  signTime: undefined,
  inPrice: undefined,
  returnVisitTime: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  stalker: [{ required: true, message: '跟踪人不能为空', trigger: 'blur' }],
  storageName: [{ required: true, message: '门店不能为空', trigger: 'blur' }],
  demand: [{ required: true, message: '客户需求不能为空', trigger: 'blur' }],
  followStatus: [{ required: true, message: '跟踪状态不能为空', trigger: 'blur' }],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const areaList = ref([])
const cityArr = ref<number[]>([])
const userList = ref<UserVO[]>([]) // 用户列表
const storageList = ref<BaseStorageVO[]>([]) // 门店列表
const selectedStorageId = ref<number | undefined>() // 选中的门店ID

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  areaList.value = await AreaApi.getAreaTree()
  cityArr.value = []

  // 获取用户列表
  try {
    const userData = await UserApi.getAllUserFilter()

    userList.value = userData ? userData : []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }

  // 获取门店列表
  try {
    const storageData = await BaseStorageApi.getBaseStorageAllDesc()
    storageList.value = storageData ? storageData : []
  } catch (error) {
    console.error('获取门店列表失败:', error)
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await CustomerApi.getCustomer(id)

      if (formData.value.province) {
        cityArr.value.push(formData.value.province)
      }
      if (formData.value.city) {
        cityArr.value.push(formData.value.city)
      }
      if (formData.value.area) {
        cityArr.value.push(formData.value.area)
      }
      if (formData.value.stalker) {
        formData.value.stalker = Number(formData.value.stalker)
      }

      if (formData.value.tags) {
        formData.value.tags = Number(formData.value.tags)
      }

      // 如果有门店名称，尝试找到对应的门店ID
      if (formData.value.storageName) {
        const storage = storageList.value.find((s) => s.storageName === formData.value.storageName)
        if (storage) {
          selectedStorageId.value = storage.storageId
        }
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as CustomerVO
    if (formType.value === 'create') {
      let res = await CustomerApi.createCustomer(data)
      if (res == '添加成功') {
        message.success(res)
      } else {
        ElMessage({
          type: 'success',
          dangerouslyUseHTMLString: true,
          message: '<strong style="color: #E73F32; font-size: 16px;">' + res + '</strong>',
          duration: 1000 * 10
        })
      }
    } else {
      let res = await CustomerApi.updateCustomer(data)
      if (res == '修改成功') {
        message.success(res)
      } else {
        ElMessage({
          type: 'success',
          dangerouslyUseHTMLString: true,
          message: '<strong style="color: #E73F32; font-size: 16px;">' + res + '</strong>',
          duration: 1000 * 10
        })
      }
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 门店选择变化处理
const handleStorageChange = (value) => {
  console.log('门店选择值:', value)
  if (value) {
    // 根据选中的门店ID查找对应的门店信息
    const selectedStorage = storageList.value.find((storage) => storage.storageId === value)
    if (selectedStorage) {
      // 将门店信息赋值给表单
      formData.value.storageName = selectedStorage.storageName
      formData.value.storageCode = selectedStorage.storageCode
      formData.value.storageId = selectedStorage.storageId
    }
  } else {
    // 清空门店信息
    formData.value.storageName = undefined
    formData.value.storageCode = undefined
    formData.value.storageId = undefined
  }
}

/** 获取跟踪状态的颜色 */
const getFollowStatusColor = (statusLabel: string) => {
  if (statusLabel === '意向') {
    return '#409eff' // 🔵 蓝色 - 意向
  } else if (statusLabel === '即将签单') {
    return '#f56c6c' // 🔴 红色 - 即将签单
  } else if (statusLabel === '已签单') {
    return '#67c23a' // 🟢 绿色 - 已签单
  } else if (statusLabel === '已放弃') {
    return '#909399' // 灰色 - 已放弃
  } else if (statusLabel === '冻结客户') {
    return '#606266' // 深灰色 - 冻结客户
  } else if (statusLabel === '已转交') {
    return '#e6a23c' // 🟡 黄色 - 已转交
  } else {
    return '#606266' // 默认颜色
  }
}

/** 重置表单 */
const resetForm = () => {
  const userInfo = getUserInfo()
  console.log('userInfo:', userInfo)
  formData.value = {
    id: undefined,
    name: undefined,
    mobile: undefined,
    telephone: undefined,
    dealStatus: undefined,
    dealTime: undefined,
    isLock: undefined,
    level: undefined,
    industry: undefined,
    tags: undefined,
    source: undefined,
    remark: undefined,
    userId: undefined,
    province: undefined,
    city: undefined,
    area: undefined,
    detailAddress: undefined,
    lng: undefined,
    lat: undefined,
    nextTime: new Date(),
    followTime: undefined,
    collectTime: undefined,
    weixin: undefined,
    qq: undefined,
    purchaseTotal: undefined,
    purchaseTimes: undefined,
    followStatus: 1,
    demand: undefined,
    stalker: userInfo.id,
    positionName: undefined,
    storageName: undefined,
    signTime: undefined,
    inPrice: undefined,
    returnVisitTime: undefined
  }
  selectedStorageId.value = undefined
  formRef.value?.resetFields()
}
</script>
<style>
/* .el-card__header {
  background-color:#66b1ff
} */
</style>
